package com.kehongborui.empmanagesys.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Properties;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-07-18
 */
public class DbUtil {
    // 数据库连接
    private static Connection conn = null;
    // 数据库用户名
    private static String username = null;
    // 数据库密码
    private static String password = null;

    // 数据库连接
    private static String url = null;

    private static String driver = null;

    static {
        Properties properties = new Properties();
        // 加载配置文件
        try {
            properties.load(new InputStreamReader(DbUtil.class.getClassLoader()
                    .getResourceAsStream("com/kehongborui/empmanagesys/util/db.properties"), "UTF-8"));
            // 从配置文件中获取 数据库用户名， 密码， url, 数据库驱动类名
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
            url = properties.getProperty("jdbc.url");
            driver = properties.getProperty("jdbc.driver");

            // 加载数据库驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() {
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }

    /**
     * 关闭数据库连接
     * @param connection
     */
    public static void closeConnection(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭结果集与 statement
     * @param rs
     * @param stmt
     */
    public static void closeRsStmt(ResultSet rs, Statement stmt) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
